<?php
/**
 * quick_curd
 * ============================================================================
 * 版权所有 2024-2099 wltx666.com，并保留所有权利。
 * 网站地址: https://wltx666.com
 * ============================================================================
 * Author: 草上飞
 * Email: wltx@alipay168.cn
 * QQ: 2719875001
 * Date: 2024/12/15
 * 描述:
 */
declare(strict_types=1);

namespace app\index\controller;

use app\BaseController;
use think\App;
use think\facade\Route;

class BaseIndex extends BaseController
{
    protected $objResult;
    protected $user_id;
    protected $user_code;
    protected $token;
    protected $unauthorized = [];//不需要token验证的接口

    protected $param = [];


    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->param = request()->filter('trim,htmlspecialchars')->param();
        $this->check_token();
    }

    public function check_token()
    {
        $this->token = request()->header('authorization');
        $controller = request()->controller();
        $action = request()->action();
        if ($this->token || !in_array('*', $this->unauthorized) && !$this->user_id) {
            if ($this->token && stripos($this->token, 'Bearer') !== 0) {
                data_return('token格式错误', 401);
            } elseif ($this->token) {
                $this->token = trim(str_replace('Bearer', '', $this->token));
            }

            //TODO 获取用户信息
            /*if (!empty($this->token)) {
                $userDecode = (new UserResult())->get_token_user($this->token, 'user_id,user_code');
                $user = $userDecode['code'] === 0 ? $userDecode['data'] : [];
                if ($user) {
                    $this->user_code = $user['user_code'];
                    $this->user_id = $user['user_id'];
                    $this->param['user_id'] = $this->user_id;//添加用户id
                }
            }*/
            if ($action && !in_array($action, $this->unauthorized) && !$this->user_id) {
                data_return('登录过期，请重新登录', 401, $this->token);
            }
        }

        if (empty($this->param['user_id'])) {
            $this->param['user_id'] = -1;
        }

    }
}
